//
//  Connection.h
//  SolarSeek
//
//  Created by Erick Fejta on 05/01/17.
//  Copyright 2005 Erick Fejta. All rights reserved.
//

#import <Cocoa/Cocoa.h>

@class Message;
@class Peer;
@class Transfer;
@class NetSocket;

#import "EnumTypes.h"

extern NSString *MakeNSStringFromInternetAddress(unsigned int address);


@interface Connection : NSObject {
	NetSocket *_socket;
	CFStreamError errorDisconnectionLast;
	BOOL		_connected;
}

- (BOOL)connected;
- (CFStreamError)errorDisconnection;

- (NSString *)addressHost;
- (NSString *)addressLocal;
- (UInt16)portHost;
- (UInt16)portLocal;

- (void)connectToHost:(NSString *)hostname onPort:(UInt16)port;
- (void)disconnect;
@end



@interface NetworkConnection : Connection {
	Message *_messageSending;
	Message *_messageSent;

	Message *_messageReceived;	
	BOOL automaticallyReadMessages;	//kvc compliant.	
	NSMutableArray *_messagesQueued;
	NSMutableArray *_messagesTransmitting;
	unsigned _lengthMessage;
	int _stateConnection;
}

- (void)sendMessagesQueued;
- (void)sendMessage:(Message *)m;
- (void)readNextMessage; //usually automatic.

- (Message *)messageReceived;
- (Message *)messageSending;
- (Message *)messageSent;

- (void)removeMessagesUnsent;

- (BOOL)hasMessagesToSend;
@end

@class UnidentifiedConnection;

@interface PeerConnection : NetworkConnection {
	Peer *_peer;
	Message *_firstMessage;
	BOOL _piercingFirewall;
}

- (id)initWithUnidentifiedConnection:(UnidentifiedConnection *)uc peer:(Peer *)peer;
- (id)initWithPeer:(Peer *)peer;
- (Peer *)peer;
- (BOOL)sentHeader;
- (BOOL)piercingFirewall;
- (unsigned)tokenFirewall;

- (void)changeSocket:(NetSocket *)socket;
- (void)connectToHost:(NSString *)hostname onPort:(unsigned)port withUsername:(NSString *)myUsername;
- (void)pierceFirewallWithToken:(int)token ForHost:(NSString *)hostname onPort:(UInt16)port;
@end

@interface ServerConnection : NetworkConnection {
	unsigned _tokenLast;
}

- (unsigned)tokenNext;

@end

@interface UnidentifiedConnection : NetworkConnection {
	id info;
	NSString *type;
}

- (id)initWithSocket:(NetSocket *)sock;

- (NSString *)name;
- (NetSocket *)socket;
- (unsigned)token;
- (NSString *)type;

- (void)setupAsConnectionToName:(NSString *)name peerConnection:(BOOL)peerconn;
- (void)setupAsPierceFirewallWithToken:(unsigned)token;

@end

@interface TransferConnection : PeerConnection {
	Transfer *_transfer;
	BOOL	_closingTransfer;
	NSData *_dataTransferred;
	NSFileHandle *_fileHandle;
	unsigned _tokenUnidentified;
	unsigned long long _transferredLast;
}

- (id)initWithUnidentifiedConnection:(UnidentifiedConnection *)uc peer:(Peer *)peer transfer:(Transfer *)transfer;
- (id)initWithUnidentifiedConnection:(UnidentifiedConnection *)uc peer:(Peer *)peer;
- (id)initWithPeer:(Peer *)peer;
- (id)initWithTransfer:(Transfer *)transfer;

- (NSData *)dataTransferred;
- (unsigned)token;
- (Transfer *)transfer;

- (void)identifyTransfer;

- (void)setTransfer:(Transfer *)transfer;

@end